import 'dart:ui';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

class LanguageController extends GetxController {
  static LanguageController get to => Get.find();

  var locale = const Locale('zh', 'CN').obs; 
  final _storage = GetStorage("locale_box");
  static const String _localeKey = "locale";

  @override
  void onInit() {
    super.onInit();
    _loadLocaleStorage(); 
    ever(locale, (newLocale) {
      Get.updateLocale(newLocale);
    });
  }

  void switchLanguage(String localeCode) {
    locale.value = localeCode == 'en' ? const Locale('en', 'US') : const Locale('zh', 'CN');
    _saveLocaleToStorage(localeCode); // 保存到本地存储
  }

  void _loadLocaleStorage() {
    final savedLocale = _storage.read<String>(_localeKey);
    if (savedLocale != null) {
      locale.value = savedLocale == 'en' ? const Locale('en', 'US') : const Locale('zh', 'CN');
    } else {
      locale.value = const Locale('zh', 'CN'); // 默认语言
    }
  }


  void _saveLocaleToStorage(String localeCode) {
    _storage.write(_localeKey, localeCode);
  }
}
